state_dir = function(state) {
  str_glue("data-raw/{str_to_lower(match_name(state))}")
}

# Downloads map, strips extra columns, and caches locally
load_50state_map = function(state, quiet=FALSE) {
  abbr = match_abb(state)
  st_map = alarm_50state_map(abbr, year=2020L)

  if (!"county" %in% colnames(st_map)) st_map$county = NA_character_

  st_fips = rep(match_fips(state), nrow(st_map))
  st_map = st_map |>
    left_join(tigris::fips_codes, by=c("state", "county")) |>
    mutate(county = case_when(
      is.numeric(county) && county >= 1000 ~ str_pad(county, width=5, pad="0"),
      is.numeric(county) ~ str_c(st_fips, str_pad(county, width=3, pad="0")),
      suppressWarnings(is.na(parse_number(county))) ~ str_c(state_code, county_code),
      str_length(county) == 5 ~ county,
      str_length(county) == 3 ~ str_c(st_fips, county)
      )) |>
    select(state, county, any_of("cd_2010"), cd_2020, pop, vap,
           starts_with("pre_"), ndv, nrv,
           starts_with("vap_"), geometry, adj)

  if (!"cd_2010" %in% colnames(st_map) && nrow(st_map) == 1) {
    st_map$cd_2010 = 1L
  }

  st_map
}


# Downloads plans and caches locally
load_50state_plans = function(state, quiet=FALSE, refresh=FORCE_REFRESH) {
  abbr = match_abb(state)
  # plans = alarm_50state_plans(abbr, stats=FALSE, year=2020L, refresh=refresh)
  plans = alarm_50state_plans(abbr, stats=FALSE, year=2020L)

  if (ncol(as.matrix(plans)) > 5001) {
    n_chain = max(plans$chain, na.rm = TRUE)
    plans = plans |>
      group_by(chain) |>
      filter(as.integer(draw) < min(as.integer(draw)) + 5000/n_chain) |>
      ungroup()
  }
  if (is.ordered(plans$district)) plans$district = as.integer(plans$district)

  plans
}
